// const JSEncrypt = require('../../utils/jsencrypt.min.js');
const axios = require('../../utils/axios');
const app = getApp();
const lmd5 = require('../../utils/md5');
const upload = require('../../utils/upload');

// const encryptRSA = (word, publicKey) => {
//   var encryptor = new JSEncrypt();
//   encryptor.setPublicKey(publicKey);
//   const rsaPassWord = encryptor.encrypt(word);
//   return rsaPassWord;
// }

Page({
  data: {
    data: {
      tel: '',
      password: ''
    },

    focusedInput: -1,
    currentPage: 0,

    publicKey: ''
  },

  onLoad(options) {

  },

  getPublicKey() {
    return new Promise((resolve, reject) => {
      if(this.data.publicKey != '') return resolve(this.data.publicKey);
      wx.login({
        success: (res) => {
          if(!res.code) throw res;
          console.log(res);
          axios.get('/tools/publicKey?code=' + res.code).then(res => {
            console.log(res);
            const { code, data, message } = res;
            if(code == 200) {
              this.setData({ publicKey: data });
              resolve(data);
            } else {
              throw message;
            }
          }).catch(err => {
            reject(err);
            wx.showModal({
              title: '错误',
              content: JSON.stringify(err),
              showCancel: false
            });
          });
        }, fail: err => {
          throw err;
        }
      });
    });
  },

  onFocusInput(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({ focusedInput: index });
  },
  onBlurInput(e) {
    this.setData({ focusedInput: -1 });
  },

  onInput(e) {
    const { type } = e.currentTarget.dataset;
    const name = 'data.' + type;
    this.setData({ [name]: e.detail.value });
  },
  onAvatarChoose(e) {
    console.log(e);
    this.setData({ 'data.uAvatar': e.detail.avatarUrl });
  },

  onNext(e) {
    const { currentPage } = this.data;
    if(currentPage < 2) {
      const { offset } = e?.currentTarget?.dataset || { offset: 1 };
      this.setData({ 
        currentPage: currentPage + offset 
      });
    } else {
      wx.navigateBack();
    }
  },

  onLogin() {
    const check = data => {
      function Toast(str) {
        wx.showToast({
          title: str,
          icon: 'error',
          duration: 1500,
          mask: true
        });
        return false;
      }
      if (!data.tel) {
        return Toast('请输入手机号');
      } else if (!data.password) {
        return Toast('请输入密码');
      } else if (data.password.length < 6) {
        return Toast('密码不能少于六位');
      }

      return true;
    }
    const { data } = this.data;
    if (!check(data)) {
      return;
    }

    // this.getPublicKey().then(() => {
    //   const { publicKey } = this.data;
    //   const encodedPassword = encryptRSA(`${Date.now()}=Time;${data.password}`, publicKey);
    const encodedPassword = lmd5.hex_md5(data.password + '7fK9pL2qR4zX8yV1wN3bU6cA5dE0gHj');
      const body = {
        pswd: encodedPassword,
        tel: data.tel
      };
      axios.get('/user', body).then(res => {
        console.log(res);
        const { code, data, message } = res;
        if (code == 200) {
          app.globalData.user = data;
          app.globalData.header = {
            Authorization: data.token
          };
          if(data.cName) {
            app.changeCompanyMode();
          }
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500,
            mask: true
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else if (code == 400) {
          wx.showToast({
            title: '密码错误',
            icon: 'error',
            duration: 1500,
            mask: true
          });
        } else if (code == 401) {
          // wx.showToast({
          //   title: '请填写',
          //   icon: 'success'
          // });
          this.onNext();
        } else if (code == 500) {
          throw message;
        }
      // }).catch(err => {
      //   console.log(err);
      //   wx.showModal({
      //     title: '错误',
      //     content: JSON.stringify(err),
      //     showCancel: false
      //   });
      // });
    });
  },

  onRegister() {
    const getCode = () => {
      return new Promise((resolve, reject) => {
        wx.login({
          success: (res) => {
            if(res.code) {
              resolve(res.code);
            } else reject(res);
          }, fail: err => {
            reject(err);
          }
        });
      });
    }

    const check = data => {
      function Toast(str) {
        wx.showToast({
          title: str,
          icon: 'error',
          duration: 1500,
          mask: true
        });
        return false;
      }
      if (!data.familyName) {
        return Toast('请输入姓');
      } else if (!data.lastName) {
        return Toast('请输入名');
      } else if (!data.uAvatar) {
        return Toast('请选择头像');
      } else if(!data.cardid) {
        return Toast('请输入身份证号');
      } else if(!isCardId(data.cardid)) {
        return Toast('身份证格式错误');
      }

      return true;
    }

    const { data } = this.data;
    if (!check(data)) {
      return;
    }
    getCode().then(code => {
      const body = {
        tel: data.tel,
        pswd: lmd5.hex_md5(data.password + '7fK9pL2qR4zX8yV1wN3bU6cA5dE0gHj'),
        code,
        familyName: data.familyName,
        lastName: data.lastName,
        uAvatar: data.uAvatar,
        gender: Number(data.cardid.slice(16, 17)) % 2,
        cardid: data.cardid
      };
      console.log(body);

      const registerData = data;
      axios.post('/user', body).then(res => {
        const { code, data, message } = res;
        console.log(res);
        if (code == 200) {
          // wx.showToast({
          //   title: '注册成功',
          //   icon: 'success',
          //   duration: 1500,
          //   mask: true
          // });
          app.globalData.user = {
            familyName: registerData.familyName,
            lastName: registerData.lastName,
            uAvatar: registerData.uAvatar,
            gender: body.gender,
            tel: body.tel,
            id: data.insertId
          };
          app.globalData.header = {
            Authorization: data.token
          };
          // setTimeout(() => {
          //   wx.navigateBack();
          // }, 1500);
          wx.showModal({
            title: '注册成功',
            content: '是否立刻前去完善简历？',
            complete: (res) => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/resume/resume',
                });
              }
            }
          })
        } else if (code == 400) {
          wx.showToast({
            title: '账号已存在，请勿重复注册',
            icon: 'error',
          });
        } else if (code == 401) {
          wx.showToast({
            title: '响应超时，请检查网络环境',
            icon: 'error',
            duration: 1500,
            mask: true
          });
        } else {
          throw message;
        }
      }).catch(err => {
        wx.showModal({
          title: '错误',
          content: JSON.stringify(err),
          showCancel: false
        });
      });
    }).catch(err => {
      wx.showModal({
        title: '错误',
        content: '获取微信登录态时出错：' + JSON.stringify(err),
        showCancel: false
      });
    });
  },
})

function isCardId(str) {
  var chinaIDCardRegExp = /^[1-9]\d{5}(19|20)\d{2}(0\d|1[0-2])([012]\d|3[01])\d{3}[0-9X]$/;
  if (!chinaIDCardRegExp.test(str)) {
      return false;
  }
  var i, lastDigit, total = 0;
  var numbers = str.split('');
  if (numbers.length != 18) {
    return false;
  }
  for (i = 0; i < 17; i++) {
      total += parseInt(numbers[i], 10) * ((Math.pow(2, 17 - i)) % 11);
  }
  lastDigit = (12 - total % 11) % 11;
  if (lastDigit === 10) {
      lastDigit = 'X';
  }
  if (lastDigit.toString() !== numbers[17].toUpperCase()) {
      return false;
  }
  var year, month, day, birthday;
  year = str.substr(6, 4);
  month = str.substr(10, 2);
  day = str.substr(12, 2);
  birthday = new Date(year, month - 1, day);
  if (birthday.getFullYear() != year ||
      birthday.getMonth() + 1 != month ||
      birthday.getDate() != day) {
      return false;
  }
  return true;
}